using System.IO;
using System.Net;

namespace Metacafe
{
    public class Worker
    {
        public bool CheckURL(string url)
        {
            if (GetNumber(url) == -1)
                return false;
            else 
                return true;
        }
        
        public string GetSource(string sourceURL)
        {
            int number          = GetNumber(sourceURL);
            if (number == -1)
                return string.Empty;
            
            string url          = string.Format("http://www.metacafe.com/fplayer.php?itemID={0}&t=site&fs=&LEID=11&prefixAdID=undefined&suffixAdID=undefined", number);
            
            string pageContent  = getPage(url);
            string decollator     = "url=\"";
            string right        = pageContent.Substring(pageContent.IndexOf(decollator) + decollator.Length);
            string urlResult    = right.Substring(0, right.IndexOf("\""));
            
            return urlResult;
        }
        
        private int GetNumber(string url)
        {
            int number              = -1;
            if(!int.TryParse(url, out number))
            {
                string t            = url;
                string decollator   = "http://www.metacafe.com/watch/";
                if (t == decollator || t.IndexOf(decollator) < 0)
                    return -1;
                string right        = t.Substring(t.IndexOf(decollator) + decollator.Length);
                string sNumber      = right.Substring(0, right.IndexOf("/"));
                if (!int.TryParse(sNumber, out number))
                {
                    return -1;
                }
            }
            return number;
        }
        
        private string getPage(string uri)
        {
            WebRequest request      = WebRequest.Create(uri);
            WebResponse response    = request.GetResponse();
            
            Stream dataStream       = response.GetResponseStream();
            StreamReader reader     = new StreamReader(dataStream);
            string responseFS       = reader.ReadToEnd();
            
            reader.Close();
            response.Close();
            
            return responseFS;
        }
    }
}
